import java.util.Arrays;

public class Heap {
    private int[] elem;
    private int usedSize;
    public Heap() {
        this.elem = new int[10];
    }
    public void initHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public void shiftDown(int usedSize, int parent) {
        int child = parent * 2 + 1;
        while(child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            if(elem[parent] < elem[child]) {
                swap(parent, child);
                parent = child;
                child = parent * 2 - 1;
            }else {
                break;
            }
        }
    }
    public void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0) {
            if(elem[parent] < elem[child]) {
                swap(parent,child);
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }
    public void offer(int val) {
        if(isFull()) {
            this.elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }
    public int poll() {
        if(isEmpty()) {
            throw new NullPointerException("堆已空");
        }
        int ret = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        shiftDown(usedSize, 0);
        return ret;
    }
    public boolean isFull() {
        return usedSize == elem.length;
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 以下是堆排序所用的代码，本人此时觉得体现出了java的不便之处
     * 如果以后类设计思想进步了，请将其重置
     */
    int[] arr = { 5,9,1,4,6,8,7,3,2 };
    public void swapArr(int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    public void shiftDownArr(int usedSize, int parent) {
        int child = parent * 2 + 1;
        while(child < usedSize) {
            if (child + 1 < usedSize && arr[child] < arr[child + 1]) {
                child++;
            }
            if(arr[parent] < arr[child]) {
                swapArr(parent, child);
                parent = child;
                child = parent * 2 - 1;
            }else {
                break;
            }
        }
    }
    public void heapSort(int[] array, int size) {
        int parent = (size - 1 - 1) / 2;
        for(int i = parent; i >= 0; i--) {
            shiftDownArr(size, i);
        }
        int end = size - 1;
        while(end > 0) {
            swapArr(0, end);
            shiftDownArr(end, 0);
            end--;
        }
    }
}
